package com.qc31.monitorlib.ui.popup

import android.view.View
import android.view.animation.AlphaAnimation
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.qc31.baselib.databinding.IncludeRecyclerMathBinding
import com.qc31.baselib.utils.toast
import com.qc31.comlib.Keys
import com.qc31.comlib.entity.VideoAlarm
import com.qc31.comlib.net.ServiceHelper
import com.qc31.monitorlib.R
import com.qc31.monitorlib.base.BaseMapActivity
import com.qc31.monitorlib.databinding.PopupRealVideoBinding
import com.qc31.monitorlib.uitls.MapUtil
import com.qc31.monitorlib.uitls.MarkerBitmapUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit

class PopupActivity : BaseMapActivity<PopupRealVideoBinding>(PopupRealVideoBinding::inflate) {
    private var mMarker: Marker? = null
    override fun initMap() {
        mAMap.uiSettings.run {
            //缩放按钮
            isZoomControlsEnabled = false
            //旋转功能
            isRotateGesturesEnabled = false
            //双指倾斜手势
            isTiltGesturesEnabled = false
            //定位按钮
            isMyLocationButtonEnabled = false
            //开启比例尺
            isScaleControlsEnabled = true
        }
    }

    private lateinit var mRecyclerVB: IncludeRecyclerMathBinding
    override fun initView() {
        mRecyclerVB = IncludeRecyclerMathBinding.bind(binding.root)
        mRecyclerVB.recyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerVB.recyclerView.adapter = mAdapter
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        carId?.let {
            startTime(carId)
        }
        initAlarms()

        val anima = AlphaAnimation(0f, 1f)
        anima.duration = 2000
        binding.flBackground.startAnimation(anima)
    }

    override fun setListener() {
        binding.rdbMapCarInfo.setOnClickListener {
            binding.flPopLocation.visibility = View.VISIBLE
            mRecyclerVB.recyclerView.visibility = View.GONE
        }
        binding.rdbMapLocation.setOnClickListener {
            binding.flPopLocation.visibility = View.GONE
            mRecyclerVB.recyclerView.visibility = View.VISIBLE
        }
        binding.ivPopupClose.setOnClickListener {
            finish()
        }
    }

    private var subscribe: Disposable? = null
    private fun getLocation(carId: String) {
        subscribe = ServiceHelper.getRepository().getGpsRInfo("", carId)
            .autoDispose(scopeProvider)
            .subscribe({
                if (it.isNullOrEmpty()) {
                    R.string.toast_no_location_msg.toast(this)
                } else {
                    val listBean = it[0]
                    listBean.run {
                        binding.lrTvPopAcc.setRightText(accTime)
                        binding.lrTvPopTime.setRightText(time)
                        binding.lrTvPopState.setRightText("$speed  km/h | $drctCn | $runStopTime")
                        binding.lrTvPopMile.setRightText("$preMile km | $mile km")
                        binding.tvPopAddress.text = addr ?: ""

                        if (glat.isEmpty() || glng.isEmpty()) return@run
                        val mLatLng = LatLng(glat.toDouble(), glng.toDouble())

                        val bitmapDes =
                            MarkerBitmapUtil.getBitmapDes(
                                this@PopupActivity,
                                carId, state, drct, carName, carPlate, iconLink, false, speed
                            )
                        if (mMarker == null) {
                            mMarker = MapUtil.addAndGetMarker(mAMap, mLatLng, bitmapDes)
                        } else {
                            mMarker?.run {
                                position = mLatLng
                                setIcon(bitmapDes)
                            }
                        }

                        MapUtil.showMapPopupLatLng(mAMap, mLatLng, 0.002)
                        videoAlarmTypes?.let { item ->
                            alarmsEntity[0].isNormal = item.contains("vsm")
                            alarmsEntity[1].isNormal = item.contains("vsh")
                            alarmsEntity[2].isNormal = item.contains("vsb")
                            alarmsEntity[3].isNormal = item.contains("vtb")
                            alarmsEntity[4].isNormal = item.contains("vsv")
                        }

                        mAdapter.setList(alarmsEntity)
                    }
                }
            }, {
                it.message?.toast(this)
            })
    }

    private val mAdapter by lazy { AlarmAdapter() }

    private val alarmsEntity = arrayListOf<VideoAlarm>()
    private fun initAlarms() {
        alarmsEntity.clear()
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_1, R.string.desc_video_alarm_1))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_2, R.string.desc_video_alarm_2))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_3, R.string.desc_video_alarm_3))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_4, R.string.desc_video_alarm_4))
        alarmsEntity.add(VideoAlarm(R.mipmap.video_alarm_5, R.string.desc_video_alarm_5))
    }


    /**
     * 开始请求
     */
    private var subscribeT: Disposable? = null
    private fun startTime(carId: String) {
        subscribeT?.dispose()
        subscribeT = Flowable.interval(0, 10, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider)
            .subscribe {
                getLocation(carId)
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        subscribe?.dispose()
        subscribe = null

        subscribeT?.dispose()
        subscribeT = null
    }


    inner class AlarmAdapter :
        BaseQuickAdapter<VideoAlarm, BaseViewHolder>(R.layout.item_video_alarm) {
        private val normal_: String = getString(R.string.desc_video_alarm_normal_)
        private val normal: String = getString(R.string.desc_video_alarm_normal)

        override fun convert(holder: BaseViewHolder, item: VideoAlarm) {
            holder.setText(R.id.tvAlarmName, item.alarmTitleId)
            holder.setImageResource(R.id.ivAlarmPic, item.alarmImgId)
            if (item.isNormal) {
                holder.setBackgroundResource(R.id.tvAlarmType, R.drawable.bg_alarm_normal_)
                holder.setText(R.id.tvAlarmType, normal_)
            } else {
                holder.setBackgroundResource(R.id.tvAlarmType, R.drawable.bg_alarm_normal)
                holder.setText(R.id.tvAlarmType, normal)
            }
        }
    }
}